package cn.gs.util.stream;

// @author gs
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class FileVector {

    public static boolean writeDoubleVector(String path, Collection<Double> set) {
        Collection<String> strs = new ArrayList<String>(set.size());
        for (Double i : set) {
            if (i == null) {
                strs.add(null);
            } else {
                strs.add(String.valueOf(i));
            }
        }
        return writeStrVec(path, strs);
    }

    public static boolean writeIntVector(String path, Collection<Integer> set) {
        Collection<String> strs = new ArrayList<String>(set.size());
        for (Integer i : set) {
            if (i == null) {
                strs.add(null);
            } else {
                strs.add(String.valueOf(i));
            }
        }
        return writeStrVec(path, strs);
    }

    public static boolean writeStrVec(String path, Collection<String> set) {
        File file = new File(path);
        file.getParentFile().mkdirs();
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(file);
            for (String s : set) {
                pw.println(s);
            }
            pw.close();
        } catch (FileNotFoundException ex) {
                        Logger.getLogger(FileVector.class.getName()).log(Level.WARNING, path, ex);
            return false;
        } finally {
            pw.close();
        }
        return true;
    }

    private static List<Double> readDoubleVec(String path) {
        List<String> set = readStrVec(path);
        List<Double> vals = new ArrayList<Double>(set.size());
        for (String s : set) {
            vals.add(Double.valueOf(s));
        }
        return vals;
    }

    private static List<Integer> readIntVec(String path) {
        List<String> set = readStrVec(path);
        List<Integer> vals = new ArrayList<Integer>(set.size());
        for (String s : set) {
            vals.add(Integer.valueOf(s));
        }
        return vals;
    }

    public static List<String> readStrVec(String path) {
        List<String> set = new LinkedList<String>();
        File file = new File(path);
        if (!file.exists()) {
            return set;
        }
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                set.add(line);
            }
        } catch (IOException ex) {
            Logger.getLogger(FileVector.class.getName()).log(Level.WARNING, path, ex);
            return null;
        } finally {
            try {
                br.close();
            } catch (IOException ex) {
            }
        }
        return set;
    }
}
